package com.base.context.processor.config;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

import com.base.context.AnnotationProcessor;
import com.base.core.type.JsonUtils;
import com.base.core.util.JsonNodeUtils;
import com.base.core.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;


public class ConfigAnnotationParser implements AnnotationProcessor<Config> {

	private Logger logger = LoggerFactory.getLogger(this.getClass());
    public static Map<String, Class<?>> configObject = new HashMap<>();
    
	@Override
	public boolean processAnnotation(Class<?> type, Config annotation) {
		logger.info("读取系统配置信息：" + type.getName());
		
		Config config = type.getAnnotation(Config.class);
		String path = "config." + config.path();
		
		ConfigAnnotationParser.configObject.put(path, type);
		
		ObjectNode node = new ObjectNode(JsonNodeFactory.instance);
		node.put("_value", config.name());

		for (Field f : type.getDeclaredFields()) {
			String name = f.getName();

			ObjectNode subNode = node.putObject(name);
			ConfigParam configParam = (ConfigParam) f.getAnnotation(ConfigParam.class);
			if (configParam != null) {
				subNode.put("name", (String) StringUtils.firstNotNull(configParam.name(), name));
				if (configParam.help() != null)
					subNode.put("help", configParam.help());
				if (configParam.min() != 0)
					subNode.put("min", configParam.min());
				if (configParam.max() != 0)
					subNode.put("max", configParam.max());
				if (configParam.type() != null)
					subNode.put("type", configParam.type().toString());
				if (configParam.label() != null)
					subNode.put("label", configParam.label());

				subNode.put("required", configParam.required());

				Class<?> fieldType = f.getType();
				if (fieldType.isEnum()) {
					subNode.set("options", JsonUtils.enumToObject(fieldType));
				}
			}
		}

		JsonNodeUtils.put(path, node);
		//可以在Spring对象容器中获取对象
		return true;
	}

}
